package com.wxd.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxd.annotation.DataFilter;
import com.wxd.modules.common.redis.SysDeptRedis;
import com.wxd.modules.sys.dao.SysRoleDao;
import com.wxd.modules.sys.entity.SysDeptEntity;
import com.wxd.modules.sys.entity.SysRoleEntity;
import com.wxd.modules.sys.service.*;
import com.wxd.modules.sys.shiro.ShiroUtils;
import com.wxd.utils.Constant;
import com.wxd.utils.PageUtils;
import com.wxd.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统角色
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
   @Autowired
   private SysRoleDeptService sysRoleDeptService;
   @Autowired
   private SysRoleMenuService sysRoleMenuService;
   @Autowired
   private SysDeptService sysDeptService;
   @Autowired
   private SysUserRoleService sysUserRoleService;
   @Autowired
   private SysDeptRedis sysDeptRedis;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    @DataFilter(subDept = true,user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String roleName= (String) params.get("roleName");
        String deptIdStr= (String) params.get("deptId");
        Long deptIdLong=null;
        List<Long> deptIdList = null;
        if(StringUtils.isNotBlank(deptIdStr))
        {
            deptIdLong= Long.valueOf(deptIdStr);
            deptIdList =sysDeptService.getSubDeptIdList(deptIdLong);
            deptIdList.add(deptIdLong);
        }
        IPage<SysRoleEntity> page =this.page(
                new Query<SysRoleEntity>().getPage(params),
                new QueryWrapper<SysRoleEntity>()
                .like(StringUtils.isNotBlank(roleName),"role_name",roleName).in(deptIdList!=null,"dept_id",deptIdList)
                .apply(params.get(Constant.SQL_FILTER)!=null, (String) params.get(Constant.SQL_FILTER))
        );
        for(SysRoleEntity sysRoleEntity:page.getRecords())
        {
            SysDeptEntity sysDeptEntity = sysDeptService.getById(sysRoleEntity.getDeptId());
            if(sysDeptEntity!=null)
            {
                sysRoleEntity.setDeptName(sysDeptEntity.getName());
            }
        }
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    /*
    在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,
    加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚
    */
    public void saveRole(SysRoleEntity role) {
        role.setCreateTime(new Date());
        this.save(role);
        /*角色与部门联系*/
        sysRoleDeptService.saveOrUpdate(role.getRoleId(),role.getDeptIdList());
        /*角色与菜单联系*/
        sysRoleMenuService.saveOrUpdate(role.getRoleId(),role.getMenuIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRoleEntity role) {
       this.updateById(role);
       /*更新角色与菜单关系*/
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
        /*更新角色与部门关系*/
        sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
        /*角色与部门关系发生变化时，更新部门缓存*/
        //得到登录角色的Id，登录角色对应着数据权限
        Long roleId = (Long) ShiroUtils.getSession().getAttribute("roleId");
        Set<String> keys = redisTemplate.keys("sys:dept:"+roleId);
        System.out.println("要删除的部门缓存keys"+keys);
        redisTemplate.delete(keys);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //删除角色
       this.removeByIds(Arrays.asList(roleIds));
       /*删除角色与用户关联*/
        sysUserRoleService.deleteBatch(roleIds);
        /*删除角色与部门关联*/
        sysRoleDeptService.deleteBatch(roleIds);
        /*删除角色与菜单关联*/
        sysRoleMenuService.deleteBatch(roleIds);
    }
}
